package com.ypz.reggie.controller;

import com.sun.java.swing.plaf.windows.WindowsDesktopPaneUI;
import com.ypz.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.tools.DiagnosticListener;
import javax.tools.FileObject;
import java.io.*;
import java.util.UUID;

/**
 * 文件的上传和下载
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.imgPath}")
    private String basePath;

    /**
     * 将上传的文件存到指定目录；
     * 指定目录在yml配置文件里设置
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {

        //原始名
        String originalFilename = file.getOriginalFilename();

        //截取原始后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID创建新的文件名，避免因文件名重复造成文件覆盖
        String fileName = UUID.randomUUID() + suffix;

        //如果目录不存在，则创建目录
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            //将文件存到指定目录
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //返回文件名称
        return R.success(fileName);
    }

    /**
     * 将刚刚上传的文件以流的方式写入页面
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        try {
            //读取文件流
            InputStream inputStream = new FileInputStream(new File(basePath + name));
            //设置响应类型
            response.setContentType("image/jpeg");
            //响应流
            ServletOutputStream outputStream = response.getOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭流
            outputStream.close();
            inputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
